/*
 * Copyright (C) 2010 恒康信息科技有限公司
 * 版权所有
 */
package com.adb.util;

import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

/**
 * 
 * @author yizhe
 * @date 2012-6-13
 */
public class BitmapLoader {
	// 内存缓存,SoftReference实现自动回收
	private static HashMap<String, SoftReference<Bitmap>> imageCache = new HashMap<String, SoftReference<Bitmap>>();

	/**
	 * 自动判断从内存还是从网络获取图片
	 * 
	 * @param imageURL
	 * @return
	 */
	public static Bitmap loadBitmap(String imageURL) {
		Bitmap bm = null;
		System.out.println("loadImage---" + imageURL);
		if (imageCache.containsKey(imageURL)) {// 从内存中获取
			System.out.println("imageCache");
			SoftReference<Bitmap> reference = imageCache.get(imageURL);
			bm = reference.get();
		}
		if (null == bm) {
			bm = ImageUtil.getImage(imageURL);
		}
		if (null == bm) {// 到网络下载
			System.out.println("loadNetBitmap");
			bm = getNetBitmap2(imageURL); // 下载图片
			if (null != bm) {
				imageCache.put(imageURL, new SoftReference<Bitmap>(bm)); // 保存到内存
				ImageUtil.saveImage(imageURL, bm);// 保存到本地
			}
		}
		if (null == bm) {
			System.out.println("loadImage---false---" + imageURL);
		} else {
			System.out.println("loadImage---success");
		}
		return bm;
	}

	// 从网络下载图片,方法2,请使用本方法下载图片,
	public static Bitmap getNetBitmap2(String imageURL) {
		Bitmap bitmap = null;
		try {
			URL url = new URL(imageURL);// 获取到路径
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();// http协议连接对象
			conn.setRequestMethod("GET");// 这里是不能乱写的，详看API方法
			conn.setConnectTimeout(9000);// 别超过10秒。
			int state = conn.getResponseCode();
			if (state == 200) {
				int length = (int) conn.getContentLength();// 获取长度
				InputStream is = conn.getInputStream();
				if (length != -1) {
					byte[] imgData = new byte[length];
					byte[] temp = new byte[512];
					int readLen = 0;
					int destPos = 0;
					while ((readLen = is.read(temp)) > 0) {
						System.arraycopy(temp, 0, imgData, destPos, readLen);
						destPos += readLen;
					}
					bitmap = BitmapFactory.decodeByteArray(imgData, 0,
							imgData.length);
				}
			}
		} catch (Exception e) {
		}
		return bitmap;
	}

}